package com.qf.controller;

import com.qf.dto.EmailLogin;
import com.qf.dto.RegistryMessage;
import com.qf.dto.TelLogin;
import com.qf.entity.EmpRole;
import com.qf.entity.Emplyee;
import com.qf.service.EmpRoleService;
import com.qf.service.EmplyeeService;
import com.qf.utils.RedisUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/emplyee")
public class RegistryController {

    @Resource
    private EmplyeeService emplyeeService;

    @Resource
    private EmpRoleService empRoleService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping("/registry")
    public String registry(@RequestBody RegistryMessage registryMessage){

        String ename = registryMessage.getEname();
        System.out.println(ename);
        Emplyee emplyee = emplyeeService.findByEname(ename);

        Emplyee emp = new Emplyee();
        emp.setEemail(registryMessage.getEemail());
        emp.setEname(registryMessage.getEname());
        emp.setEpassword(registryMessage.getEpassword());
        emp.setEtel(registryMessage.getEtel());

        String code = (String) redisUtil.get(registryMessage.getEemail());

        if (emplyee == null && code.equalsIgnoreCase(registryMessage.getCode())) {
            Emplyee e = emplyeeService.saveOne(emp);
            EmpRole empRole = new EmpRole();
            Emplyee byEname = emplyeeService.findByEname(e.getEname());

            Integer eee = byEname.getEid();
            System.out.println(eee);
            empRole.setEid(eee);
            empRole.setRid(1);
            empRoleService.saveOne(empRole);
            return "success";
        } else {
            return "username has exist";
        }
    }

    @GetMapping("/getCode/{email}")
    public String sendEmail(@PathVariable String email){
        String s = emplyeeService.sendCode(email);
        System.out.println(s);
        return s;
    }

    @PostMapping("/loginByEmail")
    public String loginByEmail(@RequestBody EmailLogin emailLogin){
        if (emailLogin != null){
            Emplyee e = emplyeeService.findByEmail(emailLogin.getEemail());

            if ( e != null && e.getEpassword().equalsIgnoreCase(emailLogin.getEpassword())){
                return "success";
            } else {
                System.out.println("失败");
                return "defeat";
            }

        } else {
            return "defeat";
        }
    }

    @PostMapping("/loginByTel")
    public String loginByTel(@RequestBody TelLogin telLogin){
        return "defeat";
    }

}
